package io.renren.modules.edu.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.JacksonUtils;
import io.renren.common.utils.PageData;
import io.renren.modules.edu.dao.TEduScientificDao;
import io.renren.modules.edu.dto.TEduScientificDTO;
import io.renren.modules.edu.entity.TEduSalaryEntity;
import io.renren.modules.edu.entity.TEduScientificEntity;
import io.renren.modules.edu.entity.TEduTeacherinfoEntity;
import io.renren.modules.edu.service.TEduScientificService;
import io.renren.modules.edu.service.TEduTeacherinfoService;
import io.renren.modules.edu.vo.ScientificFileVO;
import io.renren.modules.edu.vo.TEduSalaryVO;
import io.renren.modules.edu.vo.TEduScientificVO;
import io.renren.modules.edu.vo.TEduTeacherinfoVO;
import io.renren.modules.security.SecurityUser;
import io.renren.modules.security.UserDetail;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 科研管理表
 *
 * @author zwp zwp
 * @since 1.0.0 2022-07-11
 */
@Slf4j
@Service
public class TEduScientificServiceImpl extends ServiceImpl<TEduScientificDao, TEduScientificEntity> implements TEduScientificService {

    /**
     * 上传文件资源路径
     */
    @Value("${upload.path}")
    private String path;

    /**
     * 上传文件资源路径
     */
    @Value("${upload.uploads}")
    private String uploadsPath;

    @Value("${fileUrl}")
    private String fileUrl;

    private static final String FILE_SUFFIX = "txt,docx,doc,wps,xls,xlsx";

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private TEduTeacherinfoService tEduTeacherinfoService;

    @Override
    public void save(TEduScientificDTO tEduScientificDTO) {
        TEduScientificEntity tEduScientificEntity = JacksonUtils.obj2pojo(tEduScientificDTO, TEduScientificEntity.class);
        this.baseMapper.insert(tEduScientificEntity);
    }

    @Override
    public void update(TEduScientificDTO tEduScientificDTO) {
        TEduScientificEntity tEduScientificEntity = JacksonUtils.obj2pojo(tEduScientificDTO, TEduScientificEntity.class);
        this.updateById(tEduScientificEntity);
    }

    @Override
    public ScientificFileVO uploadFile(MultipartFile uploadFile) {
        log.info("科研文件上传");
        if (uploadFile == null) {
            //判断文件是否为空
            throw new RRException("请重新上传文件！");
        }
        // 获取源文件名
        String oldFileName = uploadFile.getOriginalFilename();
        // 获取后缀名
        String extension = FilenameUtils.getExtension(oldFileName);
        // 判断文件名是否合法
        if (!FILE_SUFFIX.contains(extension)) {
            throw new RRException("文件格式不符合要求！请重新上传文件！");
        }
        // 对文件重新命名
        String uuid = UUID.randomUUID().toString();
        String newFileName = uuid + "." + extension;
        ScientificFileVO scientificFileVO = new ScientificFileVO();
        try {
            // 判断文件夹是否存在，不存在则创建
            String filePath = DateUtils.format(new Date(), "yyyyMMdd");
            File targetFile = new File(this.path + this.uploadsPath + File.separator + filePath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            // 将文件写到服务器指定的文件
            String pathName = this.path + this.uploadsPath + File.separator + filePath + File.separator + newFileName;
            File dest = new File(pathName);
            uploadFile.transferTo(dest);
            // 将图片名称和地址传出
            scientificFileVO.setFileName(filePath + "/" + newFileName);
            scientificFileVO.setFileAddress(this.fileUrl + this.uploadsPath + "/" + filePath + "/" + newFileName);
        } catch (IOException e) {
            throw new RRException("Upload error");
        }
        return scientificFileVO;
    }

    @Override
    public void onSubmit(TEduScientificDTO dto) {
        log.info("科研提交");
        // 获取当前登录人的id
        Long userId = SecurityUser.getUserId();
        // 获取教师信息
        TEduTeacherinfoVO tEduTeacherinfoVO = tEduTeacherinfoService.queryTeacherBySysUserId(userId);
        if (tEduTeacherinfoVO == null) {
            throw new RRException("未查询到相关教师身份信息！禁止发表!");
        }
        TEduScientificEntity tEduScientificEntity = JacksonUtils.obj2pojo(dto, TEduScientificEntity.class);
        tEduScientificEntity.setEduTeacherinfoId(tEduTeacherinfoVO.getId());
        tEduScientificEntity.setPublishDate(System.currentTimeMillis());
        this.baseMapper.insert(tEduScientificEntity);
    }

    @Override
    public PageData<TEduScientificVO> queryPageData(Map<String, Object> params) {
        log.info("科研信息分页");
        // 获取当前用户
        UserDetail user = SecurityUser.getUser();
        // 获取请求对象(用于分页筛选条件)
        String page = (String) params.get("page");
        String limit = (String) params.get("limit");
        String scientificName = (String) params.get("scientificName");
        // 获取起始长度
        Integer size = Integer.valueOf(limit);
        Integer index = Integer.valueOf(page);
        // 获取教师信息
        TEduTeacherinfoVO tEduTeacherinfoVO = tEduTeacherinfoService.queryTeacherBySysUserId(user.getId());
        // 创建分页对象
        IPage<TEduScientificEntity> iPage = new Page<>(index, size);
        QueryWrapper<TEduScientificEntity> wrapper = new QueryWrapper<TEduScientificEntity>();
        wrapper.eq("edu_teacherinfo_id",tEduTeacherinfoVO.getId());
        wrapper.orderByDesc("update_date");
        if (StringUtils.isNotBlank(scientificName)) {
            wrapper.like("scientific_name", scientificName);
        }
        this.baseMapper.selectPage(iPage, wrapper);
        List<TEduScientificVO> tEduScientificVOList = JacksonUtils.listObj2pojo(iPage.getRecords(), TEduScientificVO.class);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        tEduScientificVOList.forEach(e -> {
            e.setRealName(user.getRealName());
            e.setPublishTime(simpleDateFormat.format(new Date(e.getPublishDate())));
        });
        return new PageData<TEduScientificVO>(tEduScientificVOList, iPage.getTotal());
    }

    @Override
    public TEduScientificVO queryScientificById(Long id) {
        log.info("根据id获取科研信息");
        TEduScientificEntity tEduScientificEntity = this.baseMapper.selectById(id);
        return JacksonUtils.obj2pojo(tEduScientificEntity, TEduScientificVO.class);
    }

    @Override
    public PageData<TEduScientificVO> queryPageDataAdmin(Map<String, Object> params) {
        log.info("科研信息分页(管理)");
        // 获取请求对象(用于分页筛选条件)
        String page = (String) params.get("page");
        String limit = (String) params.get("limit");
        String scientificName = (String) params.get("scientificName");
        String userName = (String) params.get("userName");
        // 获取起始长度
        Integer size = Integer.valueOf(limit);
        Integer index = Integer.valueOf(page);

        // 创建分页对象
        IPage<TEduScientificEntity> iPage = new Page<>(index, size);
        QueryWrapper<TEduScientificEntity> wrapper = new QueryWrapper<TEduScientificEntity>();
        if (StringUtils.isNotBlank(userName)) {
            // 获取教师信息
            TEduTeacherinfoVO tEduTeacherinfoVO = tEduTeacherinfoService.queryTeacherByRealName(userName);
            wrapper.eq("edu_teacherinfo_id", tEduTeacherinfoVO.getId());
        }
        if (StringUtils.isNotBlank(scientificName)) {
            wrapper.like("scientific_name", scientificName);
        }
        wrapper.orderByDesc("update_date");
        this.baseMapper.selectPage(iPage, wrapper);
        List<TEduScientificVO> tEduScientificVOList = JacksonUtils.listObj2pojo(iPage.getRecords(), TEduScientificVO.class);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        tEduScientificVOList.forEach(e -> {
            TEduTeacherinfoEntity teacherinfoEntity = tEduTeacherinfoService.getById(e.getEduTeacherinfoId());
            SysUserEntity sysUserEntity = sysUserService.getById(teacherinfoEntity.getSysUserId());
            e.setRealName(sysUserEntity.getRealName());
            e.setPublishTime(simpleDateFormat.format(new Date(e.getPublishDate())));
        });
        return new PageData<TEduScientificVO>(tEduScientificVOList, iPage.getTotal());
    }


}
